<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { 
  Microphone, 
  Headset, 
  CloseBold,
  VideoPause,
  VideoPlay
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores';
const baseURL = import.meta.env.VITE_WS_BASE_URL

const userStore = useUserStore();
const router = useRouter();

// 语音通话状态
const callStatus = ref('未连接')
const callDuration = ref('00:00')
const isMuted = ref(false)
const isSpeakerOn = ref(true)
const volume = ref(70)
const aiSpeaking = ref(null)

// 计时器
let timer = null
let startTime = null;

// 开始计时
const startTimer = () => {
  startTime = Date.now();
  timer = setInterval(() => {
    const seconds = Math.floor((Date.now() - startTime) / 1000);
    const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
    const secs = (seconds % 60).toString().padStart(2, '0');
    callDuration.value = `${mins}:${secs}`;
  }, 1000);
}

let socket;
const connect = () => {
  socket = new WebSocket(`${baseURL}/ai/api/public/ws/voice-chat?token=${userStore.token}`);

  speak();

  socket.onopen = () => {
    callStatus.value = '已连接';
  }

  socket.onmessage = async (e) => {
    console.log(e.data);
    try {
      await listen(e.data);
    } finally {
      speak();
    }
  };
  socket.onclose = (e) => {
    console.log(e)
  }
  socket.onerror = (e) => {
    console.log(e)
  }
}

const disconnect = () => {
  if (socket) {
    socket.close();
  }
}

const speak = () => {
  aiSpeaking.value = false;

  const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
  recognition.lang = 'zh-CN';
  recognition.start(); // 启动麦克风

  recognition.onresult = (event) => {
      aiSpeaking.value = null;
      const text = event.results[0][0].transcript;
      if (!text) {
        setTimeout(speak(), 1000);
      }
      socket.send(text);
  };
}

async function listen(text, voiceName = "Microsoft Xiaoxiao") {
  return new Promise(async (resolve, reject) => {
    const utterance = new SpeechSynthesisUtterance(text);
    
    utterance.onstart = () => {
      aiSpeaking.value = true;
    }

    // 设置语音结束和错误回调
    utterance.onend = () => {
      aiSpeaking.value = null;
      resolve();
    };
    
    utterance.onerror = (event) => {
      aiSpeaking.value = null;
      reject(event.error);
    };

    // 等待语音列表加载
    const getValidVoices = () => {
      const voices = speechSynthesis.getVoices();
      return voices.length > 0 ? voices : null;
    };
    
    let voices = getValidVoices();
    if (!voices) {
      await new Promise(resolve => {
        speechSynthesis.onvoiceschanged = () => {
          voices = getValidVoices();
          resolve();
        };
      });
    }
    
    utterance.voice = voices.find(v => v.name.includes(voiceName)) || 
                     voices.find(v => v.lang.startsWith('zh'));
    
    speechSynthesis.speak(utterance);
  });
}

// // 语音控制
// const toggleMute = () => {
//   isMuted.value = !isMuted.value
// }

// const toggleSpeaker = () => {
//   isSpeakerOn.value = !isSpeakerOn.value
// }

// const adjustVolume = (val) => {
//   volume.value = val
// }

const endCall = () => {
  clearInterval(timer)
  callStatus.value = '通话已结束'
  setTimeout(() => {
    router.back();
  }, 1500)
}

onMounted(() => {
  setTimeout(() => {
    startTimer();
    connect();
  }, 2000)
})

onBeforeUnmount(() => {
  clearInterval(timer)
  disconnect();
})
</script>

<template>
  <div class="voice-chat-container">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <div class="status-indicator" :class="callStatus"></div>
      <span class="status-text">{{ callStatus }}</span>
      <div class="call-duration">{{ callDuration }}</div>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content">
      <div class="ai-avatar">
        <div class="avatar-circle">
          <div class="ai-icon">AI</div>
          <div class="speaking-indicator" v-if="aiSpeaking">
            <span class="pulse-dot"></span>
            <span class="pulse-dot"></span>
            <span class="pulse-dot"></span>
          </div>
        </div>
        <div class="ai-status">{{ aiSpeaking !== null ? (aiSpeaking ? 'AI正在说话...' : 'AI正在聆听...') : '' }}</div>
      </div>
    </div>
    
    <!-- 控制按钮区 -->
    <div class="control-panel">
      <!-- <div class="control-group">
        <el-tooltip effect="dark" :content="isMuted ? '取消静音' : '静音'" placement="top">
          <el-button 
            :icon="Microphone" 
            :type="isMuted ? 'danger' : 'primary'" 
            circle 
            size="large"
            @click="toggleMute"
            :class="{ 'active-control': isMuted }"
          />
        </el-tooltip>
        <span class="control-label">麦克风</span>
      </div>
      
      <div class="control-group">
        <el-tooltip effect="dark" :content="isSpeakerOn ? '关闭扬声器' : '开启扬声器'" placement="top">
          <el-button 
            :icon="Headset" 
            :type="isSpeakerOn ? 'success' : 'info'" 
            circle 
            size="large"
            @click="toggleSpeaker"
            :class="{ 'active-control': !isSpeakerOn }"
          />
        </el-tooltip>
        <span class="control-label">扬声器</span>
      </div>
      
      <div class="control-group">
        <el-slider 
          v-model="volume" 
          :step="10" 
          :show-tooltip="false"
          @change="adjustVolume"
          vertical
          height="80px"
        />
        <span class="control-label">音量</span>
      </div> -->
      
      <div class="control-group">
        <el-tooltip effect="dark" content="结束通话" placement="top">
          <el-button 
            :icon="CloseBold" 
            type="danger" 
            circle 
            size="large"
            @click="endCall"
          />
        </el-tooltip>
        <span class="control-label">结束</span>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.voice-chat-container {
  display: flex;
  box-sizing: border-box;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(135deg, #1a2a6c, #2c3e50);
  color: #ecf0f1;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.status-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  margin-bottom: 40px;
  
  .status-indicator {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background-color: #2ecc71;
    
    &.未连接 { background-color: red; }
    &.已连接 { background-color: #2ecc71; }
    &.通话中 { background-color: #f1c40f; }
    &.通话已结束 { background-color: #e74c3c; }
  }
  
  .status-text {
    font-size: 1.2rem;
    font-weight: 600;
    letter-spacing: 1px;
  }
  
  .call-duration {
    background: rgba(255, 255, 255, 0.1);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.9rem;
    font-weight: 500;
  }
}

.main-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .ai-avatar {
    text-align: center;
    
    .avatar-circle {
      position: relative;
      width: 160px;
      height: 160px;
      margin: 0 auto 25px;
      border-radius: 50%;
      background: linear-gradient(145deg, #3498db, #8e44ad);
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
      
      .ai-icon {
        font-size: 3.5rem;
        font-weight: 700;
        color: rgba(255, 255, 255, 0.9);
      }
      
      .speaking-indicator {
        position: absolute;
        bottom: -25px;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        gap: 4px;
        
        .pulse-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #3498db;
          animation: pulse 1.2s infinite ease-in-out;
          
          &:nth-child(2) { animation-delay: 0.4s; }
          &:nth-child(3) { animation-delay: 0.8s; }
        }
      }
    }
    
    .ai-status {
      font-size: 1.4rem;
      letter-spacing: 0.5px;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    }
  }
}

.control-panel {
  display: flex;
  justify-content: center;
  gap: 40px;
  padding: 20px 0;
  
  .control-group {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    
    .el-button {
      width: 60px;
      height: 60px;
      font-size: 1.5rem;
      transition: all 0.3s ease;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
      
      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 7px 20px rgba(0, 0, 0, 0.3);
      }
      
      &.active-control {
        transform: scale(0.95);
        box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.2);
      }
    }
    
    .el-slider {
      :deep(.el-slider__runway) {
        background-color: rgba(255, 255, 255, 0.2);
      }
      
      :deep(.el-slider__bar) {
        background: linear-gradient(to top, #3498db, #2ecc71);
      }
      
      :deep(.el-slider__button) {
        width: 16px;
        height: 16px;
        border: 2px solid #3498db;
      }
    }
    
    .control-label {
      font-size: 0.9rem;
      color: rgba(255, 255, 255, 0.8);
      letter-spacing: 0.5px;
    }
  }
}

@keyframes pulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.5); opacity: 0.5; }
}
</style>